<template>
  <div class="main-layout-1">
    <div id="map"
         ref="map"
         v-loading="loading"
         element-loading-text="拼命加载中"
         element-loading-background="transparent"
    ></div>
  </div>
</template>

<script>
  import 'ol/ol.css';

  import { Map, View, Feature } from 'ol'
  import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
  import { OSM, Vector as VectorSource } from 'ol/source'
  import { fromLonLat } from 'ol/proj'
  import { Style, Fill, Stroke } from 'ol/style'
  import { MultiPolygon, Polygon } from 'ol/geom'

  import axios from 'axios'

  export default {
    name: '',
    data () {
      return {
        loading: false,
        adcodeTree: [],
        currentAdcode: undefined,
      }
    },
    mounted () {
      this.initMap()

      this.queryData('100000', 'inside')
    },
    methods: {
      initMap () {
        const view = new View({
          // center: fromLonLat([104.113164, 37.570667]),
          // zoom: 4,
          constrainResolution: true, // true 限制仅允许整数缩放级别，false 为不限制
        })
        this.map = new Map({
          target: this.$refs.map,
          view,
          layers: [
            new TileLayer({
              source: new OSM()
            })
          ],
        })
      },
      queryData (adcode, type) {
        const url = `/areas_v3/bound/geojson?code=${adcode}_full`
        this.loading = true
        axios.get(url).then(res => {
          const { status, data } = res
          if (status === 200) {
            if (type === 'inside') {
              this.currentAdcode && this.adcodeTree.push(this.currentAdcode)
              this.currentAdcode = adcode
            } else {
              this.currentAdcode = adcode
              this.adcodeTree.pop()
            }
            console.log(this.currentAdcode, this.adcodeTree)

            this.drilling(data)
          } else {
            this.$message('无下级数据')
            throw new Error()
          }
        }).catch(err => {
          throw new Error(err)
        }).finally(() => {
          this.loading = false
        })
      },
      drilling (data) {
        this.map.un('singleclick', this.clickEvent)
        this.map.removeLayer(this.outlinesLayer)
        console.log(data, data.features)
        let routeFeatures = []
        data.features.forEach(areaData => {
          const { geometry, properties: { name, level, adcode, centroid, center, parent } } = areaData
          let geometryData
          if (geometry.type === 'MultiPolygon') {
            geometryData = new MultiPolygon(geometry.coordinates)
          } else {
            geometryData = new Polygon(geometry.coordinates)
          }
          const feature = new Feature({
            geometry: geometryData.transform('EPSG:4326', 'EPSG:3857'),
            name,
            level,
            adcode,
            centroid,
            center,
            parent,
          })

          // feature.setStyle(new Style({
          //   fill: new Fill({
          //     color: [71, 137, 227, 0.3]
          //   }),
          //   stroke: new Stroke({
          //     width: 1,
          //     color: [71, 137, 227, 1],
          //   })
          // }))
          routeFeatures.push(feature)
        })
        const source = new VectorSource({
          features: routeFeatures
        })
        this.outlinesLayer = new VectorLayer({
          source,
          style: new Style({
            fill: new Fill({
              color: [71, 137, 227, 0.3]
            }),
            stroke: new Stroke({
              width: 2,
              color: [71, 137, 227, 1],
            })
          })
        })

        this.map.getView().fit(source.getExtent(), {
          duration: 500,
        })
        this.map.addLayer(this.outlinesLayer)

        // this.map.on('pointermove', e => {
        //   this.map.forEachFeatureAtPixel(e.pixel, f => {
        //     console.log(f)
        //   })
        // })

        this.map.on('singleclick', this.clickEvent)
      },
      clickEvent (e) {
        const featuresAtPixel = []
        const featuresAdcode = []
        this.map.forEachFeatureAtPixel(e.pixel, f => {
          console.log(f)
          featuresAtPixel.push(f)
          featuresAdcode.push(f.get('adcode'))

        })

        if (featuresAtPixel.length) { // 点击了内部
          this.queryData(featuresAdcode[0], 'inside')
        } else { // 点击了外部
          const parentCode = this.adcodeTree[this.adcodeTree.length - 1]
          parentCode && this.queryData(parentCode)
        }
      },
    },
  }
</script>

<style scoped>
  #map {
    width: 100%;
    height: 100%;
  }
</style>
